package com.sgb.kjwl.view.widget.transport

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextUtils
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.sgb.kjwl.R
import com.sgb.kjwl.api.NewAPIManager
import com.swgk.core.base.api.ICallBack
import com.sgb.kjwl.databinding.ViewLogisticsDriverWorkbenchBinding
import com.sgb.kjwl.model.entity.transport.DriverWorkbenchEntity
import com.sgb.kjwl.model.entity.transport.SingleItemEntity
import com.swgk.core.event.EventConstant
import com.sgb.kjwl.view.event.LogisticsEvent
import com.sgb.kjwl.view.ui.activity.self.carMaster.BusinessOpportunitySubscriptionActivity
import com.sgb.kjwl.view.ui.activity.transport.CarriageDetailActivity
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.FreightPrjDetailActivity
import com.sgb.kjwl.view.ui.activity.transport.driver.goods.GeneralPrjDetailActivity
import com.sgb.kjwl.view.ui.activity.transport.driver.order.TransportOrderDriverActivity
import com.sgb.link.router.PathLogistics
import com.swgk.core.base.model.entity.BaseEntity
import com.swgk.core.util.TimeUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * @author: 杨畔
 * @date: 4/5/21 10:14 AM
 * @Description: 司机工作台
 */
class LogisticsDriverWorkbenchView(context: Context) : FrameLayout(context) {
    private var mContext = context
    private var mBinding: ViewLogisticsDriverWorkbenchBinding = DataBindingUtil.inflate(
        LayoutInflater.from(mContext),
        R.layout.view_logistics_driver_workbench,
        null,
        false
    )

    //菜单列表
    private val mMenus = mutableListOf<SingleItemEntity>()
    private var mAdapter: LogisticsWorkbenchMenuAdapter? = null

    //承运数据
    private var mEntity: DriverWorkbenchEntity.LatelyCarrierBean? = null

    init {
        addView(mBinding.root)
        initRecycler()
        initEvent()
    }

    private fun initRecycler() {
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_driver_workbench_goods, "货源商机", true, 99))
        mMenus.add(SingleItemEntity(0, R.mipmap.ic_driver_workbench_order, "订单信息", true, 99))
        mAdapter = LogisticsWorkbenchMenuAdapter(mMenus)
        mBinding.rvLwBtn.layoutManager = GridLayoutManager(mContext, 5)
        mAdapter?.bindToRecyclerView(mBinding.rvLwBtn)
    }

    private fun initEvent() {
        mAdapter?.setOnItemClickListener { _, _, position ->
            val entity = mMenus[position]
            when (entity.leftString) {
                "货源商机" -> {
                    //设置已读
                    mMenus[0].number = 0
                    mAdapter?.notifyDataSetChanged()
                    //跳转用户中心 - 车主 - 货源商机页面
                    //改为货源订阅
                    BusinessOpportunitySubscriptionActivity.start(context)
                }
                "订单信息" -> {
                    //点击打开车主订单列表页
                    TransportOrderDriverActivity.start(context)
                }
            }
        }
        mBinding.tvLwDetail.setOnClickListener {
            mEntity?.apply {
                CarriageDetailActivity.start(context, carrierNo, 2)
            }
        }
        mBinding.tvLwAdd.setOnClickListener {
            //发布承运：新增当前司机仅一辆车且车辆信息未完善的校验，见 发布车辆和承运操作权限同意规则
            ARouter.getInstance().build(PathLogistics.CarriagePushActivity).navigation()
        }
        mBinding.llLwInvalid.setOnClickListener {
            //编辑承运 编辑承运  跳转推送承运需求页  本期不填充数据跟汤志德确认结果
            ARouter.getInstance().build(PathLogistics.CarriagePushActivity).navigation()
        }
        mBinding.tvLwMore.setOnClickListener {
            //todo 更多消息，2.0.3版本隐藏
        }
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        Log.e("workbench", "onAttachedToWindow")
        refreshData()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        Log.e("workbench", "onDetachedFromWindow")
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refresh(event: LogisticsEvent) {
        if (event.messageTag == EventConstant.EVENT_REFRESH_WORKBENCH) {
            refreshData()
        }
    }

    /**
     * 刷新数据
     */
    private fun refreshData() {
        NewAPIManager.getInstance().logisticsAPI.driverWorkbench()
            .enqueue(object : ICallBack<BaseEntity<DriverWorkbenchEntity>>() {
                override fun onSuccess(data: BaseEntity<DriverWorkbenchEntity>?) {
                    syncData(data?.data)
                }
            })
    }

    /**
     * 同步数据
     */
    @SuppressLint("SetTextI18n")
    private fun syncData(data: DriverWorkbenchEntity?) {
        if (data == null) {
            mEntity = null
            mBinding.flLwAdd.visibility = VISIBLE
            mBinding.clLwMessage.visibility = GONE
            mBinding.tvLwDetail.visibility = GONE
            return
        }

        //处理承运信息
        if ( data.latelyCarrier == null){
            mEntity = null
            mBinding.flLwAdd.visibility = VISIBLE
            mBinding.tvLwDetail.visibility = GONE
        }else{
            mEntity = data.latelyCarrier
            mBinding.flLwAdd.visibility = GONE
            mBinding.tvLwDetail.visibility = VISIBLE
            //最新消息数量
            mMenus[0].number = data.count
            mAdapter?.notifyDataSetChanged()
            //货源信息
            data.latelyCarrier?.apply {
                mBinding.tvLwLoadPlace.text = "$provinceName $cityName"
                mBinding.tvLwUnloadPlace.text = "$destProvinceName $destCityName"
                mBinding.tvLwFreight.text = "${freight}${freightUnitType}"
                mBinding.tvLwDate.text = "$shipmentTimeStr"
                //
                if (bargain != null && bargain == 0) {
                    mBinding.tvLwFreightBargain.text = "不可议价"
                } else {
                    mBinding.tvLwFreightBargain.text = "可议价"
                }
                if (messageStatus != null && messageStatus == 2) {
                    mBinding.llLwInvalid.visibility = VISIBLE
                    mBinding.ivLwExpired.visibility = VISIBLE
                } else {
                    mBinding.llLwInvalid.visibility = GONE
                    mBinding.ivLwExpired.visibility = GONE
                }
            }
        }

        mBinding.clLwMessage.visibility = GONE
        data.messageList?.takeIf {
            mBinding.clLwMessage.visibility = if (it.size == 0) GONE else VISIBLE
            it.size > 0
        }?.let {
            it[0]
        }?.apply {
            //消息
            mBinding.clLwMessage.visibility = if (TextUtils.isEmpty(content)) GONE else VISIBLE
            mBinding.tvLwMsgPlace.text =
                "$provinceName-$cityName-$districtName → $destProvinceName-$destCityName-$destDistrictName"
            spannableString(content)
            mBinding.tvLwMsgTime.text =
                TimeUtils.getGapCuountTimeFormat(updateTime, System.currentTimeMillis())
            mBinding.tvLwMsgContent.setOnClickListener {
                if (!TextUtils.isEmpty(content)) {
                    if (pattern != null) {
                        if (pattern == 1) {
                            FreightPrjDetailActivity.start(mContext, sourceNo, false, false)
                        } else {
                            GeneralPrjDetailActivity.start(mContext, sourceNo, pattern, false)
                        }
                    }
                }
            }
        }

    }

    /**
     * 获取可点击的SpannableString
     * @return
     */
    private fun spannableString(string: String?) {
        val textSpannedBuilder1 = SpannableStringBuilder()
        val textSpanned11 = android.text.SpannableString("$string ")
        val textSpanned12 = android.text.SpannableString("查看货源详情 >>")
        val foregroundColor = ForegroundColorSpan(Color.parseColor("#5792FD"))
        textSpanned12.setSpan(
            foregroundColor,
            0,
            textSpanned12.length,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
        mBinding.tvLwMsgContent.text =
            textSpannedBuilder1.append(textSpanned11).append(textSpanned12)
    }
}